<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace tensent\yspay;

use Pimple\Container;

class Client extends Container {

	/**
	 * @var string
	 */
	protected $id;

	/**
	 * @var array
	 */
	protected $providers = [];
	/**
	 * @var array
	 */
	protected $defaultConfig = [];

	/**
	 * @var array
	 */
	protected $userConfig = [];

	public function __construct(array $config = [], array $prepends = []) {
		$this->registerProviders($this->getProviders());

		parent::__construct($prepends);

		$this->userConfig = $config;
	}

	/**
	 * @return array
	 */
	public function getConfig() {
		$base = [
			// http://docs.guzzlephp.org/en/stable/request-options.html
			'http' => [
				'timeout' => 30.0,
			],
		];

		return array_replace_recursive($base, $this->defaultConfig, $this->userConfig);
	}

	/**
	 * Return all providers.
	 *
	 * @return array
	 */
	public function getProviders() {
		return array_merge([
			\tensent\yspay\Kernel\LoggerProvider::class,
			\tensent\yspay\Kernel\HttpClientProvider::class,
			\tensent\yspay\Kernel\ConfigProvider::class,
			\tensent\yspay\BasicService\ServiceProvider::class,
			\tensent\yspay\trade\TradeProvider::class,
			\tensent\yspay\merchant\MerchantProvider::class,
			\tensent\yspay\common\CommonProvider::class,
			\tensent\yspay\capital\CapitalProvider::class,
		], $this->providers);
	}

	/**
	 * @param string $id
	 * @param mixed  $value
	 */
	public function rebind($id, $value) {
		$this->offsetUnset($id);
		$this->offsetSet($id, $value);
	}

	/**
	 * Magic get access.
	 *
	 * @param string $id
	 *
	 * @return mixed
	 */
	public function __get($id) {
		return $this->offsetGet($id);
	}

	/**
	 * Magic set access.
	 *
	 * @param string $id
	 * @param mixed  $value
	 */
	public function __set($id, $value) {
		$this->offsetSet($id, $value);
	}

	/**
	 * @param array $providers
	 */
	public function registerProviders(array $providers) {
		foreach ($providers as $provider) {
			parent::register(new $provider());
		}
	}
}